package cn.yup.service.impl;

import cn.yup.anno.RequiredPermission;
import cn.yup.domain.Permission;
import cn.yup.mapper.PermissionMapper;
import cn.yup.query.QueryObject;
import cn.yup.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper  ;
    @Override
    public PageInfo findAll(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        // 当前页的数据
        List<Permission> permission =  permissionMapper.findAll();

        return new PageInfo(permission);
    }
    @Autowired
    private ApplicationContext ctx;
    @Override
    public void reload() {
        permissionMapper.deleteAll();
        Map<String,Object> beansWithAnnotation=ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beansWithAnnotation.values();
        for (Object controller : controllers){
            System.out.println("controller = " + controller);
            Method[] methods = controller.getClass().getDeclaredMethods();
            for (Method method : methods){
                if (method.isAnnotationPresent(RequiredPermission.class)) {
                    RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                    String[] strings = annotation.value();

                    System.out.println("strings[0] = " + strings[0]);
                    System.out.println("strings[1] = " + strings[1]);
                    Permission permission = new Permission();
                    permission.setName(strings[0]);
                    permission.setExpression(strings[1]);
                    permissionMapper.insert(permission);
                }
            }

        }
    }

    @Override
    public void deleteById(Long id) {
        permissionMapper.deleteById(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.findAll();
    }


}
